<template>
  <div class="app-container-flex">
    <NewFullScreen
      v-model="showDialog"
      :title="title"
      :needReturn="!flowFormType"
    >
      <template v-slot:full-button>
        <el-button
          :disabled="!canSave"
          v-if="
            !orderId &&
            $permission('assetStoreOrder:saveAndSubmit') &&
            !flowFormType
          "
          @click="saveAndSubmit()"
          >保存并提交</el-button
        >
        <el-button v-if="!flowFormType" :disabled="!canSave" @click="save()"
          >保存</el-button
        >
      </template>
      <div class="model-panel">
        <div class="model-panel-title">
          <p>{{ $t('basic_information') }}</p>
        </div>
        <div class="model-panel-body">
          <!-- form -->
          <page-form
            class="paddingBox order-model-formBox flex_wrap_start_start"
            v-model:ref-obj="formInfo.ref"
            :disabled="formInfo.disabled"
            :data="formInfo.data"
            :field-list="formInfo.fieldList"
            :rules="formInfo.rules"
            :label-width="formInfo.labelWidth"
          >
            <template v-slot:form-depotName>
              <el-input
                v-model="formInfo.data.depotName"
                class="not-mongolia"
                type="input"
                :required="true"
                :disabled="true"
                placeholder="请选择入库仓库"
              >
                <template #append>
                  <el-icon @click="selectStoreDepot"><MoreFilled /></el-icon>
                </template>
              </el-input>
            </template>
            <template v-slot:form-supplierName>
              <el-input
                type="input"
                :disabled="true"
                class="not-mongolia"
                placeholder="请选择供应商"
                v-model="formInfo.data.supplierName"
              >
                <template #append>
                  <el-icon @click="openSupplierWindow"><MoreFilled /></el-icon>
                </template>
              </el-input>
            </template>
          </page-form>
        </div>
      </div>

      <div class="model-panel">
        <div class="model-panel-title">
          <Tooltip :text="$t('detailInfo')" />
        </div>
        <div class="model-panel-body">
          <!-- 条件栏 -->
          <new-page-filter
            v-model:query="filterInfo.query"
            :filter-btn="filterInfo.list"
          >
            <template v-slot:filter-addEquipment>
              <el-button @click="addEquipment()">添加资产 </el-button>
            </template>
            <template v-slot:filter-removeEquipment>
              <el-button
                :disabled="!canRemoveEquipment"
                @click="removeEquipment()"
                >删除资产
              </el-button>
            </template>
            <template v-slot:filter-brand>
              <el-button :disabled="!canSave" @click="allSetBrand()"
                >一键设置厂家
              </el-button>
            </template>
          </new-page-filter>
          <div class="flex_full_item">
            <el-form ref="tableForm" :model="tableInfo" style="width: 100%">
              <!-- 表格 -->
              <page-table
                :refresh="tableInfo.refresh"
                :init-curpage="tableInfo.initCurpage"
                v-model:data="tableInfo.data"
                :pager="false"
                :summary="true"
                :summary-field-list="tableInfo.summaryFieldList"
                :tab-index="true"
                row-key="rowId"
                :query="filterInfo.query"
                :field-list="tableInfo.fieldList"
                :handle="tableInfo.handle"
                :row-class-name="tableRowClassName"
                :isDynamic="true"
                @handleEvent="handleEvent"
              >
                <template v-slot:col-qty="scope">
                  <el-form-item class="margin-bottom">
                    <div class="page-table-input-number-wrapper">
                      <div class="page-table-input-number-left">
                        <div class="page-table-input-number-item">
                          <el-form-item
                            v-if="scope.$index >= 0"
                            :prop="`data.${scope.$index}.qty`"
                            :rules="
                              scope.$index >= 0
                                ? [
                                    {
                                      validator: $validate.positiveAndZero,
                                      trigger: 'blur',
                                    },
                                  ]
                                : []
                            "
                          >
                            <el-input-number
                              v-model.lazy="scope.row.qty"
                              style="width: 100%; margintop: 18px"
                              clearable
                              controls-position="right"
                              :precision="
                                scope.row.qtyOperateMode === 0 ||
                                scope.row.qtyOperateMode === 2
                                  ? 0
                                  : systemConfig.qty_show_precision
                              "
                              :min="0"
                              :max="scope.row.preQty"
                              @change="
                                changeLarge(
                                  $event,
                                  scope.row,
                                  `data.${scope.$index}.qty`
                                )
                              "
                            />
                          </el-form-item>
                          <div class="page-table-input-number-item-unite">
                            <!--{{ scope.row.unitName }}-->
                          </div>
                        </div>
                      </div>
                    </div>
                  </el-form-item>
                </template>
                <template v-slot:col-price="scope">
                  <el-form-item
                    v-if="scope.$index >= 0"
                    :prop="`data.${scope.$index}.price`"
                    :rules="
                      scope.$index >= 0
                        ? [
                            {
                              validator: $validate.positiveMoneyAsset,
                              trigger: 'blur',
                            },
                          ]
                        : []
                    "
                  >
                    <el-input-number
                      v-model.lazy="scope.row.price"
                      style="width: 100%"
                      clearable
                      controls-position="right"
                      :precision="systemConfig.assets_price_precision"
                      :min="0"
                      :max="99999999"
                    />
                  </el-form-item>
                </template>
                <template v-slot:col-installCost="scope">
                  <el-form-item
                    v-if="scope.$index >= 0"
                    :prop="`data.${scope.$index}.installCost`"
                    :rules="
                      scope.$index >= 0
                        ? [
                            {
                              validator: $validate.positiveMoneyZeroAsset,
                              trigger: 'blur',
                            },
                          ]
                        : []
                    "
                  >
                    <el-input-number
                      v-model.lazy="scope.row.installCost"
                      style="width: 100%"
                      clearable
                      controls-position="right"
                      :precision="systemConfig.assets_price_precision"
                      :min="0"
                      :max="99999999"
                    />
                  </el-form-item>
                </template>
                <template v-slot:col-transportCost="scope">
                  <el-form-item
                    v-if="scope.$index >= 0"
                    :prop="`data.${scope.$index}.transportCost`"
                    :rules="
                      scope.$index >= 0
                        ? [
                            {
                              validator: $validate.positiveMoneyZeroAsset,
                              trigger: 'blur',
                            },
                          ]
                        : []
                    "
                  >
                    <el-input-number
                      v-model.lazy="scope.row.transportCost"
                      style="width: 100%"
                      clearable
                      controls-position="right"
                      :precision="systemConfig.assets_price_precision"
                      :min="0"
                      :max="99999999"
                    />
                  </el-form-item>
                </template>
                <template v-slot:col-taxCost="scope">
                  <el-form-item
                    v-if="scope.$index >= 0"
                    :prop="`data.${scope.$index}.taxCost`"
                    :rules="
                      scope.$index >= 0
                        ? [
                            {
                              validator: $validate.positiveMoneyZeroAsset,
                              trigger: 'blur',
                            },
                          ]
                        : []
                    "
                  >
                    <el-input-number
                      v-model.lazy="scope.row.taxCost"
                      style="width: 100%"
                      clearable
                      controls-position="right"
                      :precision="systemConfig.assets_price_precision"
                      :min="0"
                      :max="99999999"
                    />
                  </el-form-item>
                </template>
                <template v-slot:col-brandName="scope">
                  <el-form-item
                    v-if="scope.$index >= 0"
                    :prop="`data.${scope.$index}.brandName`"
                  >
                    <el-input
                      type="input"
                      :disabled="true"
                      class="not-mongolia"
                      placeholder="请选择厂家"
                      v-model="scope.row.brandName"
                    >
                      <template #append>
                        <el-icon @click="selectBrand(scope.$index)"
                          ><MoreFilled
                        /></el-icon>
                      </template>
                    </el-input>
                  </el-form-item>
                </template>
              </page-table>
            </el-form>
          </div>
        </div>
      </div>
    </NewFullScreen>
    <!--选择仓库-->
    <SelectDepot
      v-if="selectDepotInfo.visible"
      v-model:show-dialog="selectDepotInfo.visible"
      :check-box="false"
      :query="selectDepotInfo.query"
      :highlight-row="true"
      :check-lock="true"
      :save-empty="true"
      @callback="selectDepotCallBack"
    />
    <select-supplier
      v-if="selectProductSupplier.visible"
      v-model:show-dialog="selectProductSupplier.visible"
      :query="selectProductSupplier.query"
      :check-box="false"
      :saveEmpty="true"
      :highlight-row="true"
      :api="selectProductSupplier.api"
      @callback="selectSupplierCallback"
    />
    <!-- 添加厂家 -->
    <SelectBrand
      v-if="selectBrandInfo.visible"
      v-model:showDialog="selectBrandInfo.visible"
      :saveEmpty="true"
      :check-box="false"
      :highlight-row="true"
      @callback="selectBrandCallBack"
    />
    <CapitalSourceAdjustAssetStore
      v-if="capitalSourceAdjustInfo.visible"
      v-model:show-dialog="capitalSourceAdjustInfo.visible"
      :right-data="capitalSourceAdjustInfo.rightData"
      @callback="capitalSourceAdjustCallback"
    />
    <Select-asset
      v-if="selectAssetInfo.visible"
      v-model:show-dialog="selectAssetInfo.visible"
      :query="selectAssetInfo.query.queryMap"
      :query-params="selectAssetInfo.query.queryParams"
      :api="getInventorySurplusOrderDetailCustomizeListPage"
      :commonName="selectAssetInfo.commonName"
      tableKey="assetManageAssetStoreByAssetInventorySurplusDetail-com.slip.spd.entity.vo.asset.AssetInventorySurplusOrderDetailVO"
      :check-box="true"
      :isCommonNameSerachById="true"
      @callback="callBackAsset"
    />
  </div>
</template>

<script setup name="AssetStoreOrderModify">
import { getSupplierPage } from '@/api/core'
import { getEquipmentArchivesCustomizePage } from '@/api/equipment'
const CapitalSourceAdjustAssetStore = defineAsyncComponent(() =>
  import('../../components/capitalSourceAdjustAssetStore')
)
import {
  createAssetStoreOrder,
  createAssetStoreOrderAndSave,
  submitAssetStoreOrder,
  detailAssetStoreOrder,
  getAssetStoreOrderDetailCustomizeList,
  getInventorySurplusOrderDetailCustomizeListAll,
  getInventorySurplusOrderDetailCustomizeListPage,
  updateAssetStoreOrder,
} from '@/api/asset'
import { getCustomizeSetting } from '@/api/customize'

const { proxy } = getCurrentInstance()
const emits = defineEmits()
const props = defineProps([
  'visible',
  'title',
  'orderId',
  'surplusId',
  'surplusNo',
  'type',
  'id',
  'flowFormType',
])

const productionTimePickerOptions = ref({
  disabledDate(time) {
    return time.getTime() > Date.now() - 8.64e6
  },
})
const validityTimePickerOptions = ref({
  disabledDate(time) {
    return time.getTime() < Date.now() - 24 * 60 * 60 * 1000
  },
})
const systemConfig = ref(proxy.$store.state.permission.systemConfig)
const supplierId = ref(undefined)
const supplierName = ref(undefined)
//表单相关
const formInfo = ref({
  ref: null,
  data: {
    depotName: '',
    depotId: '',
    deptName: '',
    deptId: '',
    increaseType: 22,
  },
  fieldList: [
    {
      label: '入库单号',
      value: 'orderNo',
      type: 'input',
      disabled: true,
    },
    {
      label: '入库仓库',
      value: 'depotName',
      type: 'slot',
      require: true,
    },
    {
      label: '供应商',
      value: 'supplierName',
      type: 'slot',
      required: false,
    },
    {
      label: '入库类型',
      value: 'increaseType',
      type: 'select-model',
      code: 'increase_type',
      disabled: true,
      required: true,
    },
    {
      label: '备注',
      value: 'remark',
      type: 'textarea',
      maxlength: 200,
    },
  ],
  rules: {
    depotName: [
      { required: true, message: '请选择入库仓库', trigger: 'change' },
    ],
    supplierName: [
      { required: true, message: '请选择供应商', trigger: 'change' },
    ],
    phone: [{ validator: proxy.$validate.cellphone, trigger: 'blur' }],
    increaseType: [
      {
        required: true,
        message: '请选择入库方式',
        trigger: 'blur',
      },
    ],
  },
  labelWidth: '120px',
})
// 过滤相关配置
const filterInfo = ref({
  query: {
    customizeUserVO: {},
    queryMap: {
      orderId: {
        queryType: 'EQUALS',
        queryCategory: 'AND',
        value: props.id || props.orderId,
      },
    },
    queryParams: {
      sourceType: 52,
      sourceId: props.surplusId,
    },
  },
  list: [
    { type: 'slot', value: 'addEquipment' },
    { type: 'slot', value: 'removeEquipment' },
    { type: 'slot', value: 'brand' },
  ],
})
const selectBrandInfo = ref({
  visible: false,
  index: 0,
})

const filterSurplusInfo = ref({
  query: {
    customizeUserVO: {},
    queryMap: {
      orderId: {
        queryType: 'EQUALS',
        queryCategory: 'AND',
        value: props.surplusId,
      },
    },
    queryParams: {
      availableCalcQtyGt: 0,
    },
  },
})
const capitalSourceAdjustInfo = ref({
  visible: false,
  row: {},
  leftData: [],
  rightData: [],
})
// 表格相关
const tableInfo = ref({
  refresh: 1,
  initCurpage: 1,
  data: [],
  selections: [],
  summaryFieldList: [
    { value: 'qty', formatter: proxy.$fn.qtyFormatter },
    { value: 'price', show: 'false' },
    { value: 'sumAmount', formatter: proxy.$fn.TripartiteMethod },
  ],
  fieldList: [],
  handle: {
    fixed: 'right',
    label: '操作',
    width: '120',
    btList: [
      {
        label: '资金来源',
        event: adjustAmount,
        show: true,
      },
      {
        label: '删除',
        popconfirmText: '删除后将改变数据,是否继续？',
        event: removeProduct,
        show: true,
      },
    ],
  },
})
const selectDepotInfo = ref({
  visible: false,
  query: {
    depotAuth: 'id',
    status: 1,
    deptId: '',
    useTypeId: 2,
  },
})

const selectProductSupplier = ref({
  visible: false,
  api: getSupplierPage,
  query: {
    supplierAuth: 'supplierId',
  },
})
const selectAssetInfo = ref({
  visible: false,
  query: {
    queryMap: {
      // productId: {
      //   queryType: 'NOT_IN',
      //   queryCategory: 'AND',
      //   value: '',
      // },
      orderId: {
        queryType: 'EQUALS',
        value: props.surplusId,
      },
    },
    queryParams: {
      availableCalcQtyGt: 0,
      productIdNotIn: '',
    },
  },
  commonName: {
    label: '通用名称',
    value: 'commonName',
    asValue: 'productId',
    componentType: 'select-product',
    query: {
      queryMap: {
        type: {
          asTbName: 'core_product_new',
          columnName: '`type`',
          queryType: 'EQUALS',
          queryCategory: 'AND',
          value: '1',
        },
        status: {
          asTbName: 'core_product_new',
          columnName: '`status`',
          queryType: 'EQUALS',
          queryCategory: 'AND',
          value: '1',
        },
      },
      queryParams: {},
    },
    allowCoverFilterParams: true,
    api: getEquipmentArchivesCustomizePage,
    tableKey:
      'assetDictDialog-com.slip.spd.entity.vo.asset.settings.AssetDictVO',
    highlightRow: true,
    checkBox: false,
    show: false,
    hidden: true,
  },
})
const formRefs = ref([])

const showDialog = computed({
  get() {
    return props.visible
  },
  set(newValue) {
    emits('update:visible', newValue) // 更新父组件visible
  },
})

const canSave = computed(() => {
  return tableInfo.value.data.length
})
const canRemoveEquipment = computed(() => {
  return tableInfo.value.selections.length
})

watch(
  () => tableInfo.value.data,
  () => {
    tableInfo.value.data.forEach((row) => {
      row['calcQty'] = row['qty']
      row.sumAmount = proxy.$fn.accMul(row.qty || 0, parseFloat(row.price || 0))
    })
  },
  {
    deep: true,
  }
)

onMounted(() => {
  proxy.$nextTick(() => {
    formRefs.value = [proxy.$refs['tableForm'], formInfo.value.ref]
  })
})
function adjustAmount(row) {
  if (row.capitalSourceList) {
    capitalSourceAdjustInfo.value.rightData = row.capitalSourceList
  } else {
    const sumAmount =
      row.sumAmount + row.installCost + row.transportCost + row.taxCost
    capitalSourceAdjustInfo.value.rightData = [
      {
        code: '1',
        amount: sumAmount,
      },
    ]
  }
  capitalSourceAdjustInfo.value.visible = true
  capitalSourceAdjustInfo.value.row = row
}
function addEquipment() {
  selectAssetInfo.value.visible = true
  let ids = tableInfo.value.data.map((item) => item.productId)
  selectAssetInfo.value.query.queryParams.productIdNotIn =
    ids && ids.length ? ids.toString() : ''
}
function callBackAsset(data) {
  if (data && data.length) {
    data.forEach((item) => {
      item.surplusId = formInfo.value.data.supplierId
      item.supplierName = formInfo.value.data.supplierName
      item.installCost = 0
      item.transportCost = 0
      item.taxCost = 0
      item.preQty = item.availableQty
    })
    tableInfo.value.data = data.concat(tableInfo.value.data)
  }
}
function removeProduct(selectRow = undefined) {
  if (selectRow) {
    tableInfo.value.data = tableInfo.value.data.filter(
      (row) => row !== selectRow
    )
  } else {
    proxy
      .$confirm('删除后将改变数据,是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
      .then(() => {
        tableInfo.value.data = tableInfo.value.data.filter(
          (row) => !tableInfo.value.selections.includes(row)
        )
      })
  }
}
function capitalSourceAdjustCallback(data) {
  let row = capitalSourceAdjustInfo.value.row
  row.capitalSourceList = data
}
function openSupplierWindow() {
  selectProductSupplier.value.visible = true
}
function selectSupplierCallback(row) {
  if (row && row.id) {
    formInfo.value.data.supplierId = row.supplierId
    formInfo.value.data.supplierName = row.supplierName
  } else {
    formInfo.value.data.supplierId = ''
    formInfo.value.data.supplierName = ''
  }
  if (tableInfo.value.data.length) {
    tableInfo.value.data.forEach((item) => {
      item.supplierId = row.supplierId || -2
      item.supplierName = row.supplierName || ''
    })
  }
}
setData()
function setData() {
  let obj = {
    qty: {
      label: '数量',
      value: 'qty',
      type: 'slot',
      minWidth: '250px',
      hidden: true,
    },
    preQty: {
      label: '可入库数量',
      value: 'preQty',
      type: 'column',
      componentType: 'column',
      formatter: proxy.$fn.qtyFixedFormatter,
      show: false,
      hidden: true,
    },
    supplierName: {
      label: '供应商',
      value: 'supplierName',
      type: 'column',
      hidden: true,
    },
    price: {
      label: '单价',
      value: 'price',
      minWidth: '150px',
      type: 'slot',
      formatter: proxy.$fn.TripartiteMethod,
      permission: !proxy.$permission('assetStoreOrder:price'),
      hidden: true,
    },
    sumAmount: {
      label: '总金额',
      value: 'sumAmount',
      type: 'column',
      formatter: proxy.$fn.TripartiteMethod,
      permission: !proxy.$permission('assetStoreOrder:price'),
      hidden: true,
    },
    forceAcceptValue: {
      label: '是否强制验收',
      value: 'forceAcceptValue',
      type: 'slot',
      hidden: true,
    },
    installCost: {
      label: '安装费',
      value: 'installCost',
      minWidth: '150px',
      type: 'slot',
      formatter: proxy.$fn.TripartiteMethod,
      hidden: true,
    },
    transportCost: {
      label: '运杂费',
      value: 'transportCost',
      minWidth: '150px',
      type: 'slot',
      formatter: proxy.$fn.TripartiteMethod,
      hidden: true,
    },
    taxCost: {
      label: '税费',
      value: 'taxCost',
      minWidth: '150px',
      type: 'slot',
      formatter: proxy.$fn.TripartiteMethod,
      hidden: true,
    },
    brandName: {
      label: '厂家名称',
      value: 'brandName',
      minWidth: '250px',
      type: 'slot',
      hidden: true,
    },
  }
  tableInfo.value.fieldList = Object.values({
    ...proxy.$fn.deepClone(proxy.$fieldfList.FieldList),
    ...obj,
  })
  getCustomize()
  getSurplusCustomize()
  if (!props.id && !props.orderId) {
    formInfo.value.fieldList = formInfo.value.fieldList.filter(
      (item) => item.value !== 'orderNo'
    )
  }
}

function changeLarge(e, row, str) {
  proxy.$refs.tableForm.clearValidate(str)
}
function getList() {
  getAssetStoreOrderDetailCustomizeList(filterInfo.value.query).then((res) => {
    if (res && res.success) {
      res.data.forEach((item) => {
        item.rowId = proxy.$fn.getUid()
        supplierId.value = item.supplierId
        supplierName.value = item.supplierName
      })
      tableInfo.value.data = res.data
    }
  })
}
function getSurplusList() {
  getInventorySurplusOrderDetailCustomizeListAll(
    filterSurplusInfo.value.query
  ).then((res) => {
    if (res && res.success) {
      res.data.forEach((item) => {
        item.rowId = proxy.$fn.getUid()
        // supplierId.value = item.supplierId
        // supplierName.value = item.supplierName
        item.installCost = 0
        item.transportCost = 0
        item.taxCost = 0
        item.preQty = item.availableQty
      })
      tableInfo.value.data = res.data
    }
  })
}
// 触发事件
function handleEvent(event, data) {
  switch (event) {
    case 'tableCheck':
      tableInfo.value.selections = [...data]
      break
    case 'changePrice':
      proxy.$refs.tableForm.clearValidate(data)
      break
  }
}
// 外部流程组件也需调用
function saveAndSubmit(flowData) {
  save(true, flowData)
}
function save(isSaveAndSubmit, obj = {}) {
  formRefs.value = [proxy.$refs['tableForm'], formInfo.value.ref]
  proxy.$fn.checkForm(formRefs.value).then(() => {
    let notQtyDetails = tableInfo.value.data
      .filter((row) => !row.qty)
      .map((item) => item.productCode)
    if (notQtyDetails.length) {
      proxy.$message({
        message: `请填写产品编码为【${notQtyDetails}】的数量`,
        type: 'warning',
        duration: 3500,
        showClose: true,
      })
      return
    }
    let data = formInfo.value.data
    data.mergeDetails = tableInfo.value.data
    data.sourceType = 52
    data.sourceId = props.surplusId
    data.sourceOrderNo = props.surplusNo
    let res = checkoutPriceTotal(tableInfo.value.data)
    if (!res) {
      return
    }
    let api = data.id
      ? updateAssetStoreOrder
      : isSaveAndSubmit === true
      ? createAssetStoreOrderAndSave
      : createAssetStoreOrder
    // 如果是保存并提交
    if (isSaveAndSubmit) {
      if (proxy.$route.query.processInstanceId) {
        api = submitAssetStoreOrder
      }
      data = {
        orderData: data,
        // flowTaskCommentDto和processDefinitionKey为审批流程需要传递的参数
        flowTaskCommentDto: { approvalType: 'submit' },
        processDefinitionKey: 'assetStore',
        processInstanceId: obj.processInstanceId,
        taskId: obj.taskId,
      }
    }
    api(data).then((resp) => {
      if (resp && resp.success) {
        if (props.type === 'surplus') {
          let url = '/asset/assetManage/assetStore'
          let data = {
            urlType: 1,
            url: url,
          }
          proxy.$router.push(url)
          proxy.$store.dispatch('settings/toPage', data)
          showDialog.value = false
        } else {
          if (proxy.$route.query.processInstanceId) {
            proxy.$router.push(proxy.$route.query.backRouter)
            return
          }
          showDialog.value = false
          emits('returnModify', false)
        }
      }
    })
  })
}
function allSetBrand(selectRow = undefined) {
  selectBrandInfo.value.visible = true
  selectBrandInfo.value.index = -2
}

function selectBrand(index) {
  selectBrandInfo.value.index = index
  selectBrandInfo.value.visible = true
}
function selectBrandCallBack(row) {
  const index = selectBrandInfo.value.index
  if (row) {
    if (index === -2) {
      tableInfo.value.data.forEach((item) => {
        item.brandId = row.id
        item.brandName = row.name
      })
      return
    }
    tableInfo.value.data[index].brandId = row.id
    tableInfo.value.data[index].brandName = row.name
  } else {
    tableInfo.value.data[index].brandId = '-2'
    tableInfo.value.data[index].brandName = ''
  }
}
function checkoutPriceTotal(data) {
  for (let index = 0; index < data.length; index++) {
    const element = data[index]
    // if (
    //   !element.hasOwnProperty('capitalSourceList') ||
    //   (element.hasOwnProperty('capitalSourceList') &&
    //     !element.capitalSourceList.length)
    // ) {
    //   proxy.$message({
    //     message: `编码为【${element.productCode}】的资产字典资金来源不能为空！`,
    //     type: 'warning',
    //     duration: 3500,
    //     showClose: true,
    //   })
    //   return false
    // }
    let rowTotal = 0
    let sumAmount = element.sumAmount
    let installCost = element.installCost
    let transportCost = element.transportCost
    let taxCost = element.taxCost
    rowTotal = proxy.$fn.accAdd(sumAmount || 0, installCost || 0)
    rowTotal = proxy.$fn.accAdd(rowTotal || 0, transportCost || 0)
    rowTotal = proxy.$fn.accAdd(rowTotal || 0, taxCost || 0)
    if (
      !element.hasOwnProperty('capitalSourceList') ||
      (element.hasOwnProperty('capitalSourceList') &&
        !element.capitalSourceList.length)
    ) {
      element.capitalSourceList = [
        {
          code: '1',
          amount: rowTotal,
        },
      ]
    }
    let capitalSourceList = element.capitalSourceList
    let capitalSourceListTotal = 0
    if (capitalSourceList && capitalSourceList.length) {
      capitalSourceList.forEach((item) => {
        capitalSourceListTotal = proxy.$fn.accAdd(
          capitalSourceListTotal || 0,
          item.amount || 0
        )
      })
    }
    element._isEqualPrice = rowTotal == capitalSourceListTotal
    if (!element._isEqualPrice) {
      proxy.$message({
        message: `编码为【${element.productCode}】的资产字典，总金额+安装费+运杂费+税费为【${rowTotal}】，不等于资金来源总费用【${capitalSourceListTotal}】`,
        type: 'warning',
        duration: 3500,
        showClose: true,
      })
      return false
    }
  }
  return true
}
//选择入库仓库
function selectStoreDepot() {
  selectDepotInfo.value.visible = true
}
function selectDepotCallBack(data = undefined) {
  if (data && data.id) {
    formInfo.value.data.depotId = data.id
    formInfo.value.data.depotName = data.name
    formInfo.value.data.deptName = data.deptName || ''
    formInfo.value.data.deptId = data.deptId || ''
  } else {
    formInfo.value.data.depotId = ''
    formInfo.value.data.depotName = ''
    formInfo.value.data.deptName = ''
    formInfo.value.data.deptId = ''
  }
}

//删除产品
function removeEquipment(selectRow = undefined) {
  if (selectRow && selectRow.productId) {
    tableInfo.value.data = tableInfo.value.data.filter(
      (row) => row !== selectRow
    )
  } else {
    proxy
      .$confirm('删除后将改变数据,是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
      .then(() => {
        tableInfo.value.data = tableInfo.value.data.filter(
          (row) => !tableInfo.value.selections.includes(row)
        )
      })
  }
}
function tableRowClassName({ row = undefined }) {
  if (row.isChoice && row.codeType === 3) {
    return 'success-row'
  } else {
    return ''
  }
}
function getCustomize() {
  let param = {
    tableKey:
      'assetStoreOrderModify-com.slip.spd.entity.vo.device.store.AssetStoreOrderDetailVO',
  }
  getCustomizeSetting(param).then((res) => {
    if (res && res.success) {
      let data = res.data
      tableInfo.value.fieldList = proxy.$fn.setFieldList(
        tableInfo.value.fieldList,
        data.detail
      )
      tableInfo.value.fieldList.forEach((item) => {
        if (item.value === 'receiveQty') {
          item.hidden = true
        }
      })
      filterInfo.value.query.customizeUserVO = data
      if (props.id || props.orderId) {
        getMain()
      }
    }
  })
}
function getSurplusCustomize() {
  let param = {
    tableKey:
      'assetManageAssetStoreByAssetInventorySurplusDetail-com.slip.spd.entity.vo.asset.AssetInventorySurplusOrderDetailVO',
  }
  getCustomizeSetting(param).then((res) => {
    if (res && res.success) {
      filterSurplusInfo.value.query.customizeUserVO = res.data
      if (!props.id && !props.orderId && props.surplusId) {
        getSurplusList()
      }
    }
  })
}
function getMain() {
  detailAssetStoreOrder(props.id || props.orderId).then((resp) => {
    if (resp && resp.success) {
      formInfo.value.data = resp.data
      filterInfo.value.query.queryMap.orderId.value = props.id || props.orderId
      getList()
    }
  })
}
// 名称不要做改变，在流程引擎中需要通过refs进行调用
defineExpose({
  save,
  saveAndSubmit,
})
</script>

<style scoped></style>
